/*
 * Copyright 2020 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package cc.siyecao.mapper.provider.entity;

import lombok.experimental.Accessors;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 实体表接口，记录实体和表的关系
 *
 * @author liuzh
 */
@Accessors(fluent = true)
public class EntityTable extends Table<EntityColumn> {

    protected EntityTable() {
    }

    protected EntityTable(Class<?> entityClass) {
        this.entityClass = entityClass;
    }

    public static EntityTable of(Class<?> entityClass) {
        EntityTable entityTable = new EntityTable( entityClass );
        return entityTable;
    }

    /**
     * 返回所有字段
     *
     * @return 所有字段
     */
    public List<EntityField> fields() {
        return columns().stream().map( EntityColumn::field ).collect( Collectors.toList() );
    }

    /**
     * 添加列
     */
    public void addColumn(EntityColumn column) {
        //不重复添加同名的列
        if (!columns().contains( column )) {
            if (column.field().getDeclaringClass() != entityClass()) {
                columns().add( 0, column );
            } else {
                columns().add( column );
            }
            column.entityTable( this );
            propertyMap.put( column.field().getName(), column );
        } else {
            //同名列在父类存在时，说明是子类覆盖的，字段的顺序应该更靠前
            EntityColumn existsColumn = columns().remove( columns().indexOf( column ) );
            columns().add( 0, existsColumn );
            propertyMap.put( existsColumn.field().getName(), existsColumn );
        }
    }

    //</editor-fold>

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof EntityTable)) return false;
        EntityTable entity = (EntityTable) o;
        return table().equals( entity.table() );
    }

    @Override
    public int hashCode() {
        return Objects.hash( table() );
    }

    @Override
    public String toString() {
        return table();
    }
}
